import SockJS from "sockjs-client/dist/sockjs.min.js";
import Stomp from "stompjs";

export const initFirst = (wsUrl) => {
  if (wsUrl) {
    return new Promise((resolve, reject) => {
      // 建立连接对象
      let socket = new SockJS("http://127.0.0.1" + wsUrl);
      // 获取STOMP子协议的客户端对象
      const stompClient = Stomp.over(socket);
      console.log('stompClient',stompClient);
      stompClient.debug = false;

      // 定义客户端的认证信息,按需求配置
      let headers = {
        // Authorization: 用户身份验证信息,
      };
      // 向服务器发起websocket连接
      stompClient.connect(
        headers,
        () => {
          console.log('stompClient',stompClient);
          resolve(stompClient); // 连接成功，解析 Promise
        },
        (err) => {
          reject(err); // 连接失败，拒绝 Promise
        }
      );
    });
  }
};

export const connection = (mystompClient, topic, callback) => {
  mystompClient.subscribe(topic, function (msg) {
    // 订阅服务端提供的某个topic
    callback(msg);
  });
};

export const disconnect = (mystompClient, wsUrl) => {
  if (wsUrl) {
    if (mystompClient) {
      mystompClient.disconnect();
    }
  }
};
